<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');
session_start();

class User extends CI_Controller {

	function index() {
		$this -> load -> model('user_model');
		$this -> register();
	}

	function authenticate() {
		// this class used for pages which need authenticated user view
		$data['notification2'] = "You don't have a credential to see the following page, please login first.";
		$this -> load -> view('view_login', $data);
	}

	function login() {
		// user login 

		// form validation
		$this -> load -> library('form_validation');
		$this -> form_validation -> set_rules('username', 'Username', 'trim|required|max_length[20]|alpha_numeric|xss_clean');
		$this -> form_validation -> set_rules('password', 'Password', 'trim|required|max_length[20]|alpha_numeric|xss_clean');

		if ($this -> form_validation -> run() == FALSE) {
			//validation error
			$data['loginerror'] = (validation_errors());

			$this -> load -> view('view_login', $data);
		} else {
			//to database
			$this -> load -> model('user_model');
			$username = $this -> input -> post('username');
			$password = $this -> input -> post('password');
			$check = $this -> user_model -> check_login($username, $password);

			if ($check == 0) {
				// user valid to login
				$_SESSION['userObject'] = $this -> user_model -> getUserByUsername($username);
				$_SESSION['username'] = $_POST['username'];
				redirect('mainpage');
			} elseif ($check == 1) {
				//user haven't activate their id through email
				$data['notification'] = "Please activate id";
				$this -> load -> view('view_login', $data);
			} elseif ($check == 2) {
				// incorrect username or password
				$data['notification'] = "Please check your username or password";
				$this -> load -> view('view_login', $data);
			}
		}
	}

	function register() {
		//sign up
		
		//form validation
		$this -> load -> library('form_validation');

		$this -> form_validation -> set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[20]|alpha_numeric|xss_clean|callback_username_notexist');
		$this -> form_validation -> set_rules('fname', 'First Name', 'trim|required|max_length[55]|xss_clean');
		$this -> form_validation -> set_rules('lname', 'Last Name', 'trim|required|max_length[55]|xss_clean');
		$this -> form_validation -> set_rules('email', 'Email', 'trim|required|xss_clean|max_length[45]|valid_email|callback_email_notexist');
		$this -> form_validation -> set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[20]|alpha_numeric|xss_clean');
		$this -> form_validation -> set_rules('password_conf', 'Confirmation Password', 'trim|required|min_length[6]|alpha_numeric|matches[password]|xss_clean');
		$this -> form_validation -> set_rules('year', 'Year', 'required|xss_clean');
		$this -> form_validation -> set_rules('month', 'Month', 'required|xss_clean');
		$this -> form_validation -> set_rules('day', 'Day', 'required|xss_clean');
		$this -> form_validation -> set_rules('phone', 'Contact Number', 'trim|required|min_length[8]|max_length[15]|numeric|xss_clean');
		$this -> form_validation -> set_rules('location', 'Location', 'trim|required|max_length[45]|xss_clean');
		$this -> form_validation -> set_rules('company', 'Company', 'trim|max_length[45]|xss_clean');
		$this -> form_validation -> set_rules('role', 'Role', 'required|xss_clean');

		if ($this -> form_validation -> run() == FALSE) {
			//validation error
			$data['registererror'] = (validation_errors());
			$this -> load -> view('view_register', $data);
		} else {
			//to database
			$interests = $this -> input -> post('interests');
			$roles = $this -> input -> post('role');
			$interestString = "";
			$count = 0;
			//parse user interest by ;
			if ($interests != NULL) {
				if (count($interests) > 0) {

					foreach ($interests as $interest) {
						if ($count == 0) {
							$interestString .= $interest;
						} else {
							$interestString .= ";" . $interest;
						}
						$count++;
					}
				}
			}
			//parse user role by;
			$roleString = "";
			$count = 0;
			if (count($roles) > 0) {
				foreach ($roles as $role) {
					if ($count == 0) {
						$roleString .= $role;
					} else {
						$roleString .= ";" . $role;
					}
					$count++;
				}
			}

			$this -> load -> model('user_model');
			$username = $this -> input -> post('username');
			$fname = $this -> input -> post('fname');
			$lname = $this -> input -> post('lname');
			$password = $this -> input -> post('password');
			$email = $this -> input -> post('email');
			$phone = $this -> input -> post('phone');
			$location = $this -> input -> post('location');
			$company = $this -> input -> post('company');
			$role = $this -> input -> post('role');
			$dob = $this -> input -> post('year') . "-" . $this -> input -> post('month') . "-" . $this -> input -> post('day');

			$activation_code = $this -> _random_string(10);

			$this -> user_model -> register_user($username, $password, $fname, $lname, $email, $phone, $location, $company, $roleString, $interestString, $activation_code, $dob);

			//email confirmation 
			$this -> load -> library('email');

			$config['protocol'] = 'mail';
			$config['wordwrap'] = TRUE;
			$config['smtp_timeout'] = '7';
			$config['smtp_host'] = 'ssl://smtp.gmail.com';
			$config['smtp_port'] = 465;
			$config['smtp_user'] = 'ideascover@gmail.com';
			$config['smtp_pass'] = 'airlangga';
			$config['charset'] = 'utf-8';
			$config['mailtype'] = 'text';
			$config['newline'] = "\r\n";
			$this -> email -> initialize($config);

			$this -> email -> from('ideascover@gmail.com', 'IDeascover Admin');
			$this -> email -> to($email);
			$this -> email -> subject('Registration Confirmation');
			$this -> email -> message("
This is an auto-generated email, please do not reply to this notification
=======================================================
			
Dear $fname $lname,
			
You have successfully been registered to Ideascover!

	Your username is : $username

Please click the following link to verify your email and finish creating your account.

http://ideascover.site90.net/user/register_confirm/$activation_code	
			
			

-Ideascover Team-","Confirm Registration");
			$this -> email -> send();
			
			$data['success'] = "Please check your email for confirming your account";
			$this -> load -> view('view_login', $data);
			
			}

	}

	function register_confirm() {
		//confirming registration from links 
		
		$this -> load -> model('user_model');
		$registration_code = $this -> uri -> segment(3);

		if ($registration_code == '') {
			echo 'error no registration code';
			exit();
		}

		$registration_confirmed = $this -> user_model -> confirm_registration($registration_code);

		if ($registration_confirmed != '') {
			//correct link
			$data['success'] = "Please login on the left";
			$this -> load -> view('view_login', $data);

		} else {
			//incorrect registration link
			$data['notification2'] = "registration failed, please check your registration code";
			$this -> load -> view('view_login', $data);
		}
	}

	function username_notexist($username) {
		// check username already used or not
		$this -> load -> model('user_model');
		$this -> form_validation -> set_message('username_notexist', 'username already exist');
		if ($this -> user_model -> check_username($username)) {
			return false;
		} else {
			return true;
		}

	}

	function email_notexist($email) {
		//check email already used or not
		$this -> load -> model('user_model');
		$this -> form_validation -> set_message('email_notexist', 'email already exist');
		if ($this -> user_model -> check_email($email)) {
			return false;
		} else {
			return true;
		}

	}

	function _random_string($length) {
		//to create random activation code number
		$len = $length;
		$base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789';
		$max = strlen($base) - 1;
		$activatecode = '';
		mt_srand((double)microtime() * 1000000);
		while (strlen($activatecode) < $len + 1)
			$activatecode .= $base{mt_rand(0, $max)};

		return $activatecode;
	}

	/*
	 * Function to destroy session and user logout
	 */ 
	function logout() {
		//$this->session->set_userdata('logged_in', FALSE);
		unset($_SESSION['username']);
		unset($_SESSION['userObject']);
		redirect('mainpage');
	}



/*
 * This functions is for showing the manage profile page with all of user profile's attributes
 * No parameters, returns none
 */ 
	function manage_profile(){

		include("authenticate.php");
		$username = $_SESSION['username'];//get the username from the global session
		$this->load->model('user_model');
		$data['user']=$this->user_model->getUserByUsername($username);
		$this->load->view('view_manage_profile', $data);
		
	}
	
	/*
	 * This function is for updating user profile that has been changed, also send email notification when user change his/her 
	 * primary email address
	 * returns none
	 */ 
	function update_profile(){
		
		
		$interests = $this -> input -> post('interests');
			$roles = $this -> input -> post('user_role');
			$interestString = "";
			$count = 0;
			if ($interests != NULL) {
				if (count($interests) > 0) {

					foreach ($interests as $interest) {
						if ($count == 0) {
							$interestString .= $interest;
						} else {
							$interestString .= ";" . $interest;
						}
						$count++;
					}
				}
			}

			$roleString = "";
			$count = 0;
			if (count($roles) > 0) {
				foreach ($roles as $role) {
					if ($count == 0) {
						$roleString .= $role;
					} else {
						$roleString .= ";" . $role;
					}
					$count++;
				}
			}
		
			$this -> load -> model('user_model');
			
			$email = $this -> input -> post('user_email');
			$phone = $this -> input -> post('user_contact');
			$location = $this -> input -> post('user_location');
			$company = $this -> input -> post('user_company');
			$username = $this->input->post('username');
			
			$data = array(
				'user_email' => $email,
				'user_phone' => $phone,
				'user_company' => $company,
				'user_location' => $location,
				'user_interests' => $interestString,
				'user_role' => $roleString
			);
			
			
			$this->user_model->update_profile($data, $username);
			
			
				//track activity
				$this->load->model('feed_model');
				$this->feed_model->trackUserActivity($username, " updated the profile page.");
				
			
			// email notification for email changed	
			$this -> load -> library('email');

			$config['protocol'] = 'mail';
			$config['wordwrap'] = TRUE;
			$config['smtp_timeout'] = '7';
			$config['smtp_host'] = 'ssl://smtp.gmail.com';
			$config['smtp_port'] = 465;
			$config['smtp_user'] = 'ideascover@gmail.com';
			$config['smtp_pass'] = 'airlangga';
			$config['charset'] = 'utf-8';
			$config['mailtype'] = 'text';
			$config['newline'] = "\r\n";
			//$config['smtp_host'] = 'smtp.gmail.com';
			$this -> email -> initialize($config);

			$this -> email -> from('ideascover@gmail.com', 'IDeascover Admin');
			$this -> email -> to($email);
			$this -> email -> subject('Change Email');
			$this -> email -> message("
This is an auto-generated email, please do not reply to this notification
=======================================================
			
Dear $username,
			
You have successfully changed your primary email to $email

From now on any messages from Ideascover will be sent to this email
			
			

-Ideascover Team-", 'Change Email');
			$this -> email -> send();
			//echo $this->email->print_debugger();
			
			
			
			echo redirect(base_url("user/profile/$username"));
	}


	function profile($username) {
		// view user profile 	
		if (!isset($username)) {
			redirect('user/');
		}

		if (!isset($_SESSION)) {
			session_start();
		}

		if (isset($_SESSION['username'])) {
			$this -> load -> model('feed_model');
			$followed_by_username = $_SESSION['username'];
			$data['subscriptionIsTrue'] = $this -> feed_model -> checkSubscriptionUser($username, $followed_by_username);
		}

		$this -> load -> model('user_model');
		$this -> load -> model('idea_model');
		$data['user'] = $this -> user_model -> getUserByUsername($username);
		$data['ideas'] = (array)$this -> idea_model -> getIdeasOfUser($username);
		$this -> load -> view('view_userprofile', $data);
	}

	function username_exist($username) {
		//checking if user is exist
		$this -> load -> model('user_model');
		$this -> form_validation -> set_message('username_exist', 'Username Not Exist');
		if ($this -> user_model -> check_username($username)) {
			return true;
		} else {
			
			return false;
		}
	}

	function forgetPassword() {
		$data['forget'] = "Please fill the box below";
		$this -> load -> view('view_login', $data);

	}

	function resetPasswordCode() {
		//reset password sending link to email
		$this -> load -> library('form_validation');

		$this -> form_validation -> set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[20]|alpha_numeric|xss_clean|callback_username_exist');

		if ($this -> form_validation -> run() == FALSE) {
			//validation error
			$data['forget'] = (validation_errors());
			$this -> load -> view('view_login', $data);
		} else {
			$username = $this -> input -> post('username');
			$this -> load -> model('user_model');
			$this -> load -> model('idea_model');
			$user = $this -> user_model -> getUserByUsername($username);
			$this -> load -> library('email');

			$config['protocol'] = 'mail';
			$config['wordwrap'] = TRUE;
			$config['smtp_timeout'] = '7';
			$config['smtp_host'] = 'ssl://smtp.gmail.com';
			$config['smtp_port'] = 465;
			$config['smtp_user'] = 'ideascover@gmail.com';
			$config['smtp_pass'] = 'airlangga';
			$config['charset'] = 'utf-8';
			$config['mailtype'] = 'text';
			$config['newline'] = "\r\n";
			//$config['smtp_host'] = 'smtp.gmail.com';
			$this -> email -> initialize($config);

			$this -> email -> from('ideascover@gmail.com', 'IDeascover Admin');
			$this -> email -> to($user -> user_email);
			$this -> email -> subject('Password Reset');
			
			$this -> email -> message("
This is an auto-generated email, please do not reply to this notification
=======================================================
			
Dear $username,
			
You have requested a password reset.

For security reason please click this link to reset your password.

http://ideascover.site90.net/user/resetPassConf/$user->user_activation_code
			
			

-Ideascover Team-", "Change Password");
			$this -> email -> send();

			$data['success'] = "Please check your email for reseting password";
			$this -> load -> view('view_login', $data);
			//redirect('mainpage');

		}
	}

	function resetPassConf() {
		//checking email for reseting password
		$this -> load -> model('user_model');
		$forgetPassCode = $this -> uri -> segment(3);

		if ($forgetPassCode == '') {
			//no code
			echo 'error no registration code';
			exit();
		}

		$code_confirmed = $this -> user_model -> confirm_registration($forgetPassCode);

		if ($code_confirmed != '') {
			//correct
			$data['reset'] = "Please enter your username and new password";
			$this -> load -> view('view_login', $data);

		} else {
			//error
			$data['notification2'] = "registration failed, please check your reset password code";
			$this -> load -> view('view_login', $data);
		}

	}

	function resetPassword() {
		//reset password for forget password link
		$this -> load -> library('form_validation');

		$this -> form_validation -> set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[20]|alpha_numeric|xss_clean|callback_username_exist');
		$this -> form_validation -> set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[20]|alpha_numeric|xss_clean');
		$this -> form_validation -> set_rules('password_conf', 'Confirmation Password', 'trim|required|min_length[6]|alpha_numeric|matches[password]|xss_clean');

		if ($this -> form_validation -> run() == FALSE) {
			//validation error
			$data['reset'] = (validation_errors());
			$this -> load -> view('view_login', $data);
			//echo "error";
		} else {
			$this -> load -> model('user_model');
			$username = $this -> input -> post('username');
			$password = $this -> input -> post('password');

			$this -> user_model -> update_password($username, $password);

			$data['success'] = "Please Login on the Left";
			$this -> load -> view('view_login', $data);

		}

	}
	
	function changePassword(){
		//change password inside my settings
		$this -> load -> library('form_validation');

		$this -> form_validation -> set_rules('oldpassword', 'Old password', 'trim|required|min_length[6]|max_length[20]|alpha_numeric|xss_clean');
		$this -> form_validation -> set_rules('newpassword', 'Password', 'trim|required|min_length[6]|max_length[20]|alpha_numeric|xss_clean');
		$this -> form_validation -> set_rules('newpassword_conf', 'Confirmation Password', 'trim|required|min_length[6]|alpha_numeric|matches[newpassword]|xss_clean');

		if ($this -> form_validation -> run() == FALSE) {
			//validation error
			$data['change'] = (validation_errors());
			$this -> load -> view('view_login', $data);
			//echo "error";
		} else {
			//to database
			$username = $_SESSION['username'];
			$this -> load -> model('user_model');
			$oldpassword = $this -> input -> post('oldpassword');
			$newpassword = $this -> input -> post('newpassword');
			$check = $this -> user_model -> change_password($username, $oldpassword, $newpassword);

			if ($check == 0) {
				//success 
			$this -> load -> view('view_login');
			redirect('user/manage_profile/'.$username);
			} elseif ($check == 1) {
			$data['notification2'] = "wrong old password";
			$data['retry'] = 'Retry change password';
			$this -> load -> view('view_login', $data);
			}
		}
		
	}

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
